package com.huluobo.jetpackkotlindemo.coroutine

import android.os.Bundle
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.huluobo.jetpackkotlindemo.databinding.ActivityRetrofitBinding
import com.huluobo.jetpackkotlindemo.livedata_viewmodel.AdViewModel
import com.huluobo.jetpackkotlindemo.viewbinding.BaseActivity
import kotlinx.coroutines.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * Created by lc on 2022/12/16.
 */
class RetrofitActivity : BaseActivity<ActivityRetrofitBinding>() {
    override fun getViewBinding(): ActivityRetrofitBinding =
        ActivityRetrofitBinding.inflate(layoutInflater)

    val retorfit = Retrofit.Builder().baseUrl("https://api.github.com/")
        .addConverterFactory(GsonConverterFactory.create()).build()

    val apiService = retorfit.create(ApiService::class.java)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

//        apiService.queryData().enqueue(object : Callback<List<User>> {
//            override fun onResponse(call: Call<List<User>>, response: Response<List<User>>) {
//                mViewBinding.tvText.text = Gson().toJson(response.body())
//            }
//
//            override fun onFailure(call: Call<List<User>>, t: Throwable) {
//
//            }
//        })

        //使用协程来发起网络请求
        //retrofit2.9可以直接支持在main中调用协程来进行线程的切换
        val job = Job()
//        CoroutineScope(job).launch(Dispatchers.Main) {
//            val result = apiService.queryData1()
//            mViewBinding.tvText.text = Gson().toJson(result)
//        }

        //如果retrofit2.8以下 不支持直接在main调用协程,则需要协程的切换
        CoroutineScope(job).launch(Dispatchers.Main) {
            val result = withContext(Dispatchers.IO) {
                apiService.queryData1()
            }
            mViewBinding.tvText.text = Gson().toJson(result)
        }

        //会把协程绑定到当前的lifecycle对象上,
        lifecycleScope.launchWhenCreated {
            Log.i("TagA", "launchWhenCreated")
        }
        lifecycleScope.launchWhenResumed {
            Log.i("TagA", "launchWhenResumed")
        }
        lifecycleScope.launchWhenStarted {
            Log.i("TagA", "launchWhenStarted")
        }
    }
}